package com.chixing.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * JDBC:
 *      PreparedStatement pstmt = connection.preparedSatement();
 *
 * 该类用于获得sqlSession 与 关闭sqlSession
 * sqlSession (1)封装了PreparedStatement -- 执行SQL
 *            (2) 一级缓存 cache
 *
 * SqlSessionFactory 重量级资源：
 *      连接数据库：加载与读取一次   mybatis-config.xml (数据源 + 导入了mapper文件)
 *
 */
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;

    /**
     * static: 在类加载的时候执行，只执行一次
     *  sqlSessionFactory 重量级资源，
     */
    static{
        InputStream is = MybatisUtil.class.getResourceAsStream("/config/mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }
    public static SqlSession getSqlSession(){
        sqlSession =  sqlSessionFactory.openSession();
        return sqlSession;
    }
    public static void  closeSqlSession(){
        if(sqlSession !=null)
            sqlSession.close();
    }


}
